<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户管理</title>
  <style>
    body {
      font-size: 20px;
    }

    #root li {
      list-style: none;
      margin-bottom: 10px;
    }

    #root li span {
      margin-right: 20px;
    }
  </style>
</head>

<body>
  <ul id="root"></ul>
  <hr>
  <div>
    <div>
      <input type="text" id="name">
    </div>
    <div>
      <input type="number" id="age">
    </div>
    <div>
      <button id="btn">添加用户</button>
    </div>
  </div>


  <script type="module">
    import request from './js/http.js'
    import createHtml from './js/createhtml.js'
    const btn = document.querySelector('#btn')

    // 方法体
    let methods = {
      edit(id) {
        // 把按钮文字修改
        btn.innerHTML = '修改用户'
        btn.value = id
        request('/users/' + id).then(data => {
          for (let key in data) {
            document.getElementById(key) && (document.getElementById(key).value = data[key])
          }
        })
      },
      del(id) {
        if (confirm('真删除')) {
          request('/users/' + id, 'delete').then(() => location.reload(true))
        }
      }
    }

    addEventListener('load', () => {
      request('/users').then(data => {
        document.querySelector('#root').innerHTML = createHtml(data)
      })
    })

    // ul绑定事件，委托它来对li事件处理
    document.querySelector('#root').addEventListener('click', function (e) {
      // console.log(e.target.className,e.target.dataset);
      // 修改
      // console.log(e.target.className);
      // 前置+，强转为整型
      // let id = +e.target.dataset.id
      let id = Number(e.target.dataset.id)
      methods[e.target.className](id)
      // [e.target.className](id)
      // eval(`${e.target.className}(${id})`)
    })

    btn.addEventListener('click', function () {
      let id = this.value ? +this.value : 0
      /* let data = {};
      ['name', 'age'].forEach(key => {
        data[key] = document.getElementById(key).value
      }) */
      let data = ['name', 'age'].reduce((prev, key) => {
        prev[key] = document.getElementById(key).value
        return prev
      }, {})

      request('/users/' + id, 'put', data).then(ret => location.reload(true))
    })

    function edit(id) {
      // 把按钮文字修改
      btn.innerHTML = '修改用户'
      btn.value = id
      request('/users/' + id).then(data => {
        for (let key in data) {
          document.getElementById(key) && (document.getElementById(key).value = data[key])
        }
      })
    }




  </script>

</body>

</html>